//
//  ChatCell.m
//  tcpoctest
//
//  Created by gump on 11/8/12.
//  Copyright (c) 2012 gump. All rights reserved.
//

#import "ChatCell.h"
#import <QuartzCore/QuartzCore.h>

#import "giftMessageInfo.h"

#import "GiftMessageDataSource.h"
#import "chatDataSource.h"
#import "ChatContentInfo.h"

#import "TelepathyDataSource.h"
#import "telepathyInfo.h"

@implementation ChatCell

static CGFloat textMarginHorizontal = 15.0f;
static CGFloat textMarginVertical = 10.0f;
static CGFloat messageTextSize = 14.0f;

@synthesize sent,cellType, textView, messageView, timeLabel, avatarImageView, balloonView,contentImgView,audioControlView,message;

#pragma mark -
#pragma mark Static methods

+(CGFloat)textMarginHorizontal {
    return textMarginHorizontal;
}

+(CGFloat)textMarginVertical {
    return textMarginVertical;
}

+(CGFloat)maxTextWidth {
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
        return 240.0f;
    } else {
        return 400.0f;
    }
}

+(CGSize)messageSize:(NSString*)message {
    return [message sizeWithFont:[UIFont systemFontOfSize:messageTextSize] constrainedToSize:CGSizeMake([self maxTextWidth], CGFLOAT_MAX) lineBreakMode:NSLineBreakByWordWrapping];
}

+(UIImage*)balloonImage:(BOOL)sent isSelected:(BOOL)selected {
    if (sent == YES) {
        return [[UIImage imageNamed:@"myMessage.png"] stretchableImageWithLeftCapWidth:20.0f topCapHeight:25.0f];
        
    }else{
        return [[UIImage imageNamed:@"yourMessage.png"] stretchableImageWithLeftCapWidth:20.0f topCapHeight:25.0f];
    }
}

#pragma mark -
#pragma mark Object-Lifecycle/Memory management

-(id)initMessagingCellWithReuseIdentifier:(NSString*)reuseIdentifier {
    if (self = [super initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier]) {
        self.selectionStyle = UITableViewCellSelectionStyleNone;
        
        balloonView = [[UIImageView alloc] initWithFrame:CGRectZero];
        balloonView.autoresizingMask = UIViewAutoresizingFlexibleHeight;
        
        textView.font = [UIFont systemFontOfSize:16.0f];
        
        contentImgView = [[UIImageView alloc] initWithFrame:CGRectZero];
        
        timeLabel = [[UILabel alloc] initWithFrame:CGRectZero];
        avatarImageView = [[UIImageView alloc] initWithImage:nil];
        
        audioControlView = [[UIImageView alloc] initWithFrame:CGRectZero];
        audioControlView.image = [UIImage imageNamed:@"btn_audioPlay_press.png"];
        audioControlView.userInteractionEnabled = YES;
        [balloonView addSubview:audioControlView];
        
        self.avatarImageView.layer.cornerRadius = 3.0;
        self.avatarImageView.layer.masksToBounds = YES;
        self.avatarImageView.layer.borderColor = [UIColor colorWithWhite:0.0 alpha:0.2].CGColor;
        self.avatarImageView.layer.borderWidth = 1.0;
        self.avatarImageView.userInteractionEnabled = YES;
        


        self.timeLabel.font = [UIFont boldSystemFontOfSize:12.0f];
        self.timeLabel.textColor = [UIColor darkGrayColor];
        self.timeLabel.backgroundColor = [UIColor clearColor];
        
        self.contentImgView.layer.cornerRadius = 7.0;
        self.contentImgView.layer.masksToBounds = YES;
        
        [self.contentView addSubview: self.balloonView];
        
        [self.contentView addSubview: self.timeLabel];
        [self.contentView addSubview: self.avatarImageView];
        
        
        UILongPressGestureRecognizer *recognizer =
        [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPress:)];
        [recognizer setMinimumPressDuration:1.0f];
        [self addGestureRecognizer:recognizer];
        
        singleTouch = [[UITapGestureRecognizer alloc] initWithTarget:self action:nil];
        singleTouch.delegate = self;
        [self addGestureRecognizer:singleTouch];
        
        self.voiceTimeLabel = [[UILabel alloc] initWithFrame:CGRectZero];
        self.voiceTimeLabel.hidden = YES;
        self.voiceTimeLabel.backgroundColor = [UIColor clearColor];
        [self.contentView addSubview:self.voiceTimeLabel];
        
        self.StateLabel = [[UILabel alloc] initWithFrame:CGRectZero];
        self.StateLabel.backgroundColor = COLOR_CHATSTATE_SENDING;
        self.StateLabel.layer.cornerRadius = 2;
        self.StateLabel.textColor = [UIColor whiteColor];
        self.StateLabel.font = [UIFont boldSystemFontOfSize:10];
        self.StateLabel.textAlignment = NSTextAlignmentCenter;
        [self.contentView addSubview:self.StateLabel];
        
    }
    
    return self;
}

-(void)handleTapPress
{
    if (self.ccinfo != nil) {
        if (self.ccinfo.ichatReadState == CRS_SENDFAIL)
        {
            [DataControl shareControl].chatDS.reSendInfo = self.ccinfo;
            
            [[DataControl shareControl].UICommendDS addUICommand:UC_CHAT_POPRESENDMENU];
        }
        else
        {
            switch (self.cellType) {
                case CT_TEXT:
                {
                    
                }
                    break;
                    case CT_TELEPATHY:
                {
                    if (self.ccinfo != nil) {
                        telepathyInfo *tinfo = [[DataControl shareControl].TelepathyDS
                                                GetTelepInfoByID:self.ccinfo.strid];
                        
                        if (tinfo != nil) {
                            switch (tinfo.iStateType) {
                                case TGT_FAIL:
                                {
                                    [[DataControl shareControl].UICommendDS addUICommand:UC_CHAT_TELEPATHYFAIL];
                                }
                                    break;
                                case TGT_SUCCESS:
                                {
                                    FirendInfo *fi = [[DataControl shareControl] SearchInfo:tinfo.correctmail];
                                    if (fi != nil) {
                                        [DataControl shareControl].currentFI = fi;
                                        
                                        [[ViewManager sharedViewManager] showView:VI_PERSONINFO
                                                                 withIsRemoveCurV:true
                                                                    withDirection:VD_RIGHT];
                                    }
                                }
                                    break;
                                case TGT_GUESS:
                                {
                                    [DataControl shareControl].TelepathyDS.curinfo = tinfo;
                                    
                                    [[ViewManager sharedViewManager] showView:VI_PERSONINFO
                                                             withIsRemoveCurV:true
                                                                withDirection:VD_RIGHT];
                                }
                                    break;
                                default:
                                    break;
                            }
                        }
                    }
                    
                }
                    break;
                case  CT_VOICE:
                {
                    [[NSNotificationCenter defaultCenter] postNotificationName:NOTIFICATION_VOICE_PRESS object:audioControlView];
                }
                    break;
                case CT_IMAGE:
                {
                    [[NSNotificationCenter defaultCenter] postNotificationName:NOTIFICATION_IMG_PRESS object:message];
                }
                    break;
                case CT_GIFT:
                {
                    giftMessageInfo *gminfo = [[DataControl shareControl].giftMessageDS GetInfoByIndex:self.iRow];
                    if (gminfo != nil) {
                        
                        [DataControl shareControl].giftMessageDS.curSelectInfo = gminfo;
                        
                        [[DataControl shareControl].UICommendDS addUICommand:UC_CHAT_POPGIFTMENU];
                    }
                }
                    break;
                default:
                    break;
            }
        }
    }

}

#pragma mark UIGestureRecognizerDelegate methods
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    return YES;
}

- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer
{
    CGPoint pointInCell = [gestureRecognizer locationInView:self];
    if (gestureRecognizer == singleTouch )
    {
        if(CGRectContainsPoint(balloonView.frame, pointInCell)) {
        [self handleTapPress];
        }
        else if (CGRectContainsPoint(self.avatarImageView.frame, pointInCell))
{
    [self pressHeadImage];
}
    } else {
        [[NSNotificationCenter defaultCenter] postNotificationName:NOTIFICATION_CELL_PRESS object:nil]; 
    }
    
    [[NSNotificationCenter defaultCenter] postNotificationName:NOTIFICATION_CELL_PRESS object:nil];
    
    return YES;
}


#pragma mark -
#pragma mark Layouting

- (void)layoutSubviews {
    CGSize textSize;
    switch (self.cellType) {
        case CT_TEXT:
        case CT_TELEPATHY:
        {
            textSize = textView.frame.size;
        }
            break;
        case  CT_VOICE:
        {
            textSize = CGSizeMake(31, 31);
        }
            break;
        case CT_IMAGE:
        {
            textSize = contentImgView.image.size;
        }
            break;
        default:
            break;
    }

    CGSize dateSize = [self.timeLabel.text sizeWithFont:self.timeLabel.font
                                               forWidth:[ChatCell maxTextWidth]
                                          lineBreakMode:NSLineBreakByClipping];
    
    CGRect ballonViewFrame = CGRectZero;//气泡的坐标
    CGRect textViewFrame = CGRectZero;//显示文字的label的坐标
    CGRect timeLabelFrame = CGRectZero;//显示时间的label的坐标
    CGRect avatarImageFrame = CGRectZero;//显示用户头像的坐标
    CGRect contentImageFrame = CGRectZero;//显示聊天图片的坐标
    CGRect audioControlBtnFrame = CGRectZero;//显示语音的btn的坐标
    CGRect voiceTimeFrame = CGRectZero;//显示语音时间的坐标
    CGRect stateLabelFrame = CGRectZero;//显示状态的坐标
    
    timeLabelFrame = CGRectMake((WINDOW_WIDTH - dateSize.width)/2,
                                0.0f,
                                dateSize.width,
                                dateSize.height);
    
    if (self.sent == YES) {
        
        //设置气泡的frame
        switch (self.cellType) {
            case CT_TEXT:
            case CT_TELEPATHY:
            {
                ballonViewFrame = CGRectMake(self.frame.size.width - (textSize.width + 2*textMarginHorizontal + 60.0f),
                                             timeLabelFrame.size.height + BALLOONSIZE,
                                             textSize.width + 2*textMarginHorizontal + 10,
                                             textSize.height + 2*textMarginVertical);
                
                stateLabelFrame = CGRectMake(self.frame.size.width - (textSize.width + 2*textMarginHorizontal + 92.0f),
                                             timeLabelFrame.size.height + STATESIZE,
                                             30, 12);

            }
                break;
            case  CT_VOICE:
            {
                ballonViewFrame = CGRectMake(self.frame.size.width - (textSize.width + 2*textMarginHorizontal + 50.0f),
                                             timeLabelFrame.size.height + BALLOONSIZE,
                                             textSize.width + 2*textMarginHorizontal,
                                             textSize.height + textMarginVertical);
                
                stateLabelFrame = CGRectMake(self.frame.size.width - (textSize.width + 2*textMarginHorizontal + 82.0f),
                                             timeLabelFrame.size.height + STATESIZE,
                                             30, 12);

            }
                break;
            case CT_IMAGE:
            {
                ballonViewFrame = CGRectMake(self.frame.size.width - (textSize.width + 2*textMarginHorizontal + 40.0f),
                                             timeLabelFrame.size.height + BALLOONSIZE,
                                             textSize.width + textMarginVertical + 10,
                                             textSize.height + textMarginVertical);
                
                stateLabelFrame = CGRectMake(self.frame.size.width - (textSize.width + 2*textMarginHorizontal + 72.0f),
                                             timeLabelFrame.size.height + STATESIZE,
                                             30, 12);

            }
                break;
            default:
                break;
        }
        
        textViewFrame = CGRectMake(10,
                                   10,
                                   textSize.width,
                                   textSize.height);
        
        avatarImageFrame = CGRectMake(self.frame.size.width - 45.0f,
                                      ballonViewFrame.origin.y + 1,
                                      40.0f, 40.0f);
        
        contentImageFrame = CGRectMake(textMarginVertical/2,
                                       textMarginVertical/2,
                                       textSize.width, textSize.height);
        
        audioControlBtnFrame = CGRectMake(10, 5, textSize.width, textSize.height);

        voiceTimeFrame = CGRectMake(self.frame.size.width - (textSize.width + 2*textMarginHorizontal + 75.0f),
                                    timeLabelFrame.size.height + 20,
                                    20, 20);
        
                
    } else {
        //设置气泡的frame
        switch (self.cellType) {
            case CT_TEXT:
            case CT_TELEPATHY:
            {
                ballonViewFrame = CGRectMake(50.0f,
                                             timeLabelFrame.size.height + BALLOONSIZE,
                                             textSize.width + 2*textMarginHorizontal + 10,
                                             textSize.height + 2*textMarginVertical);
            }
                break;
            case  CT_VOICE:
            {
                ballonViewFrame = CGRectMake(50.0f,
                                             timeLabelFrame.size.height + BALLOONSIZE,
                                             textSize.width + 2*textMarginHorizontal,
                                             textSize.height + textMarginVertical);
            }
                break;
            case CT_IMAGE:
            {
                ballonViewFrame = CGRectMake(50.0f,
                                             timeLabelFrame.size.height + BALLOONSIZE,
                                             textSize.width + textMarginVertical + 10,
                                             textSize.height + textMarginVertical);
            }
                break;
            default:
                break;
        }
        
        textViewFrame = CGRectMake(20, 10, textSize.width, textSize.height);
        
        avatarImageFrame = CGRectMake(5.0f, ballonViewFrame.origin.y + 1, 40.0f, 40.0f);
        
        contentImageFrame = CGRectMake(8+textMarginVertical/2,
                                       textMarginVertical/2,
                                       textSize.width, textSize.height);
        
        audioControlBtnFrame = CGRectMake(20, 5, textSize.width, textSize.height);
        
        voiceTimeFrame = CGRectMake(55.0f + textSize.width + 2*textMarginHorizontal,
                                    timeLabelFrame.size.height + 20,
                                    20, 20);
        
        stateLabelFrame = CGRectMake(55.0f + textSize.width + 2*textMarginHorizontal,
                                    timeLabelFrame.size.height,
                                    30, 20);
        
    }
    
    self.balloonView.image = [ChatCell balloonImage:self.sent isSelected:self.selected];
    
    self.balloonView.frame = ballonViewFrame;
                              
    if (self.avatarImageView.image != nil) {
    self.avatarImageView.frame = avatarImageFrame;
    }
                              
    if (self.timeLabel.text != nil) {
    self.timeLabel.frame = timeLabelFrame;
    }
    [textView removeFromSuperview];
    [contentImgView removeFromSuperview];
    [audioControlView removeFromSuperview];
    
     switch (self.cellType) {
     case CT_TEXT:
         case CT_TELEPATHY:
     {
      self.textView.frame = textViewFrame;
      [self.balloonView addSubview: self.textView];
         
         self.voiceTimeLabel.hidden = YES;
         
     }
     break;
     case  CT_VOICE:
     {
      self.audioControlView.frame = audioControlBtnFrame;
      [self.balloonView addSubview: self.audioControlView];
         self.voiceTimeLabel.frame = voiceTimeFrame;
         self.voiceTimeLabel.hidden = NO;
     }
     break;
     case CT_IMAGE:
     {
        self.contentImgView.frame = contentImageFrame;
        [self.balloonView addSubview: self.contentImgView];
         
         self.voiceTimeLabel.hidden = YES;
     }
     break;
     default:
         {
             self.voiceTimeLabel.hidden = YES;
         }
     break;
     }
    
    self.StateLabel.frame = stateLabelFrame;
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:NO];
    
    [self setNeedsLayout];
    
    if (selected == YES) {
        [self becomeFirstResponder];
    } else {
        [self resignFirstResponder];
    }
}

-(void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated {
    
}

-(void)setEditing:(BOOL)editing animated:(BOOL)animated {
	
}

#pragma mark -
#pragma mark UIGestureRecognizer-Handling

- (void)handleLongPress:(UILongPressGestureRecognizer *)longPressRecognizer {
    if (longPressRecognizer.state != UIGestureRecognizerStateBegan) {
        return;
    }
    
    if ([self becomeFirstResponder] == NO) {
        return;
    }
    
    self.balloonView.image = [ChatCell balloonImage:self.sent isSelected:YES];

    
    if (self.iSection == 0) {
        switch (self.cellType) {
                case CT_TEXT:
                case CT_TELEPATHY:
            case CT_IMAGE:
                case CT_VOICE:
            {
                    UIMenuController * menu = [UIMenuController sharedMenuController];
                    [menu setTargetRect:self.balloonView.frame inView:self];
                
                    [menu setMenuVisible:YES animated:YES];
            }
                break;
            default:
                break;
        }
    }
    
}

-(BOOL)canBecomeFirstResponder {
    return YES;
}

-(BOOL)canPerformAction:(SEL)action withSender:(id)sender{
    if (action == @selector(copy:)) {
        if(self.cellType == CT_TEXT){
          return YES;
        }else{
          return NO;
        }
    }if (action == @selector(delete:)) {
        switch (self.cellType) {
            case CT_TEXT:
                case CT_VOICE:
                case CT_IMAGE:
                case CT_TELEPATHY:
            {
                return YES;
            }
                break;
                
            default:
            {
                return NO;
            }
                break;
        }
    }
    else {
        return [super canPerformAction:action withSender:sender];
    }
}

-(void)copy:(id)sender {
    self.balloonView.image = [ChatCell balloonImage:self.sent isSelected:NO];
    UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
    [pasteboard setString:message];
}

- (void)delete:(id)sender
{
    self.balloonView.image = [ChatCell balloonImage:self.sent isSelected:NO];
    
    [[DataControl shareControl].chatDS DelCurChatArrObjectByRow:self.iRow];
}

-(void)pressHeadImage
{
    if ([DataControl shareControl].currentFI != nil) {
        if ([[DataControl shareControl].currentFI.mail isEqualToString:
            [DataControl shareControl].personDS.uinfo.mail]) {
            [[ViewManager sharedViewManager] showView:VI_USERINFO
                                     withIsRemoveCurV:false
                                        withDirection:VD_RIGHT];
        }
        else if(self.sent)
        {
            [[ViewManager sharedViewManager] showView:VI_USERINFO
                                     withIsRemoveCurV:false
                                        withDirection:VD_RIGHT];
        }
        else
        {
            [[ViewManager sharedViewManager] showView:VI_PERSONINFO
                                     withIsRemoveCurV:false
                                        withDirection:VD_RIGHT];
        }
    }
}

@end
